package com.ansion.basedb.database.sql;

import androidx.annotation.NonNull;

import java.util.ArrayList;
import java.util.List;

/**
 * created by zhaoyuntao
 * on 10/11/2023
 * description: 注意：SQLTable中的versionCode一旦定义后续版本就不应更改，
 * 新增字段时，指定该字段的版本号，会触发upgrade操作。
 */
public class SQLTable {
    private final String tableName;
    private final int versionCode;
    private final List<SQLField> fields;
    private boolean fts;
    private boolean mutPrimaryKey;
    private final List<SQLUnionIndex> unionIndexes = new ArrayList<>();

    public SQLTable(@NonNull String tableName, int versionCode) {
        this.tableName = tableName;
        this.versionCode = versionCode;
        fields = new ArrayList<>();
    }

    public SQLTable fts(boolean fts) {
        this.fts = fts;
        return this;
    }

    public SQLTable addField(@NonNull SQLField field) {
        return addField(versionCode, field);
    }

    public SQLTable addField(int versionCode, @NonNull SQLField field) {
        field.setTableName(tableName);
        field.setVersionCode(versionCode);
        fields.add(field);
        return this;
    }

    public SQLTable addUnionIndex(SQLUnionIndex unionIndex) {
        unionIndexes.add(unionIndex);
        return this;
    }

    public String getTableName() {
        return tableName;
    }

    public int getVersionCode() {
        return versionCode;
    }

    public boolean isFts() {
        return fts;
    }

    public SQLTable mutPrimaryKey(boolean mutPrimaryKey) {
        this.mutPrimaryKey = mutPrimaryKey;
        return this;
    }

    public boolean isMutPrimaryKey() {
        return mutPrimaryKey;
    }

    public List<String> getPrimaryKeyName() {
        List<String> primaryKeys = new ArrayList<>();
        for (SQLField field : fields) {
            if (field.isPrimaryKey()) {
                primaryKeys.add(field.getName());
            }
        }
        return primaryKeys;
    }

    @NonNull
    public List<SQLField> getFields() {
        return fields;
    }

    public List<SQLUnionIndex> getUnionIndexes() {
        return unionIndexes;
    }
}
